import re
import time

import ffmpeg

from util import FileUtils

kthread =4
# 全抽帧
def get_frames(input_file,output_file):
    # input_file = 'C:\\test\\video\\test.mp4'
    # output_file = 'C:\\test\\video/ffmpeg/image-%5d.jpg'
    out, err = (
        ffmpeg
            .input(input_file)
            .output(output_file)
            .run(quiet=False, overwrite_output=True)
    )
    if out == b'':
        print('do nothing')


# 按一定的频率抽帧
def get_frames_by_rate(input_file,output_file,fps):
    #测试视频的帧率为30帧每秒 如果每秒抽5帧
    #input_file = 'C:\\test\\video\\test.mp4'
    #output_file = 'C:\\test\\video\\ffmpeg/image-%5d.jpg'
    #fps=fps=1 每一秒抽帧一次
    fps = 'fps=fps=' + str(fps)
    out, err = (
        ffmpeg
            .input(input_file, ss=0)
            # .output(output_file, r='1', f='image2')
            .output(output_file, vf=fps, f='image2')
            .run(quiet=False, overwrite_output=True)
    )
    if out == b'':
        print('do nothing')

def convertVideo(videoPath,option,videoName=False):
    ret = {}
    output_file = 'C:\\test\\video/ffmpeg/image-%d.jpg'
    args = ['-y','-threads',kthread if option['nThread'] is None else option['nThread'],'-i',videoPath]
    listOutfiles = []
    print("videoPath is ",videoPath)
    print("option is: ", option)
    print("option is: ",option['outputs'])
    fps = 'fps=fps='
    if 'processFps' in option.keys():  # op['fps'] is not None:
        args.append('-r')
        args.append(option['processFps'])
        fps += str(option['processFps'])
        print("fps is ", fps)
    for op in option['outputs']:
        out = {'type':op['type'],'outputPath':op['outputPath']}
        listOutfiles.append(out)
        if 'scaleH' in op.keys():#op['scaleH'] is not None:
            args.append('-vf')
            args.append('scale=-1:'+op['scaleH'])

        if 'type' in op.keys():#op['type'] == 'image':
            frameDir = op['outputPath']
            args.append('-q:v')
            args.append('3')
            args.append(frameDir+'%d.jpg')
            if videoName:
                vname = FileUtils.getFilepreName(FileUtils.getFileName(videoPath))
                output_file = frameDir + vname+'-%d.jpg'
            else:
                output_file = frameDir+'%d.jpg'
        else:
            args.append('-c:v')
            args.append('libx264')
            args.append('-preset')
            args.append('veryfast')
            args.append('-crf')
            args.append('26')
            args.append('-f')
            args.append('mp4')
            args.append(op['outputPath'])
    print("-------------fps is ",fps)
    out, err = (
        ffmpeg.input(videoPath).output(output_file, vf=fps, f='image2').run(quiet=False, overwrite_output=True)
    )
    for f in listOutfiles:
        data, images= FileUtils.scanpath(f['outputPath'],'jpg')
        images.sort(key=lambda x: int(re.findall(r"\d+", FileUtils.getFileName(x))[0]))
        f['images'] = images
    #listOutfiles.sort(key=lambda x: int(re.findall(r"\d+", x)[0]))
    ret['outputs'] = listOutfiles
    return ret
    pass

# 按指定时间片段抽帧
def get_frames_by_times():
    times = [1, 5, 8, 10]
    for time in times:
        input_file = 'C:\\test\\video\\test.mp4'
        output_file = 'C:\\test\\video/ffmpeg/image-' + str(time) + '.jpg'
        out, err = (
            ffmpeg
                .input(input_file, ss=time)
                .output(output_file, vframes='1', f='image2')
                .run(quiet=False, overwrite_output=True)
        )
        if out == b'':
            print('do nothing')


if __name__ == '__main__':
    #input_file = 'C:\\test\\video\\test.mp4'
    #output_file = 'C:\\test\\video\\ffmpeg/image-%5d.jpg'
    input_file = "C:\\test\\docker\\var\\aiparents\\test\\video\\private\\record-video\\1637113276328.mp4"
    output_file = 'C:\\test\\docker\\var\\aiparents\\test\\video\\private\\record-video\\%d.jpg'
    get_frames(input_file,output_file)
    starttime = time.time()
    fps = 3
    #get_frames_by_rate(input_file,output_file,fps)
    endtime = time.time()
    print(starttime)
    print(endtime)
    print(endtime - starttime)
    option = {}
    #convertVideo(input_file,option)
